define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue'], function ($, undefined, Backend, Table, Form, Vue) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/goods/index' + location.search,
                    add_url: 'goods/goods/add',
                    edit_url: 'goods/goods/edit',
                    del_url: 'goods/goods/del',
                    multi_url: 'goods/goods/multi',
                    import_url: 'goods/goods/import',
                    table: 'goods',
                }
            });

            var table = $("#table");

            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='cate_id']", form)
                    .addClass("selectpage")
                    .data("source", "category/selectpagetree")
                    .data("primaryKey", "id")
                    .data("field", "name")
                    .data("orderBy", "id desc");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false,
                commonSearch: true,
                searchFormVisible: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false, sortable: true},
                        {field: 'cate_id', title: __('Cate_id'), visible:false, operate: 'LIKE %...%'},
                        {field: 'category.name', title: __('Cate_id'), operate: false},
                        {field: 'goods_sn', title: __('Goods_sn'), operate: 'LIKE'},
                        {field: 'goods_name', title: __('Goods_name'), operate: 'LIKE',formatter: Table.api.formatter.content},
                        {field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'spec_sum', title: __('商品库存'), operate: false},
                        // {field: 'brand', title: __('Brand'), operate: 'LIKE'},
                        // {field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images},
                        // {field: 'params', title: __('Params'), operate: false},
                        {field: 'price', title: __('Price'), operate:'BETWEEN', sortable: true},
                        {field: 'is_index', title: __('Is_index'), operate: false, formatter: Table.api.formatter.toggle},
                        // {field: 'original_price', title: __('Original_price'), operate: false},
                        // {field: 'limit_num', title: __('Limit_num'), operate: false},
                        // {field: 'stock_type', title: __('Stock_type'), searchList: {"place":__('Stock_type place'),"pay":__('Stock_type pay')}, formatter: Table.api.formatter.normal, operate: false},
                        // {field: 'service_ids', title: __('Service_ids'), operate: false},
                        // {field: 'dispatch_type', title: __('Dispatch_type'), operate: false},
                        // {field: 'dispatch_ids', title: __('Dispatch_ids'), operate: false},
                        // {field: 'likes', title: __('Likes'), operate: false, sortable: true},
                        // {field: 'views', title: __('Views'), operate: false, sortable: true},
                        {field: 'sales', title: __('Sales'), operate: false, sortable: true},
                        {field: 'weigh', title: __('Weigh'), operate: false, sortable: true},
                        {field: 'status', title: __('Status'), searchList: {"up":__('Status up'),"hidden":__('Status hidden'),"down":__('Status down')}, formatter: Table.api.formatter.status},
                        // {field: 'show_sales', title: __('Show_sales'), operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, sortable: true},
                        // {field: 'updatetime', title: __('Updatetime'), operate: false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'goods/goods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'goods/goods/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'goods/goods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            // ajaxGetSpecInput();
            var goods_id = $("input[name='goods_id']").val();
            ajaxGetSpecGroup($("#c-cate_id").val(),goods_id)
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };

    var specGroup;
    $(document).on('change', "#c-cate_id", function (e, first) {
        var cate_id = $(this).val();
        if(cate_id){
            ajaxGetSpecGroup(cate_id)
        }else{
            $("#goods_spec_table2").html('')
        }

        return false;
    });

    $(document).on("change", "#c-is_index", function(){
        //开关切换后的回调事件
        // var is_index = $(this).val();
        // if(is_index == 1) {
        //     $('.exchange_coupon_id').removeClass('hide');
        // }else {
        //     $('.exchange_coupon_id').addClass('hide');
        // }
    });

    $(document).on('click', "#addSpecInput", function () {
        ajaxGetSpecInput()
    });

    $(function () {
        $(document).on("click", '.delete_item', function (e) {
            if ($(this).text() == '禁用') {
                // $(this).parent().parent().find('input').removeAttr('disabled');
                $(this).next().val(0);
                $(this).addClass('btn-info');
                $(this).removeClass('btn-danger');
                $(this).text('启用');
            } else {
                $(this).next().val(1);
                $(this).addClass('btn-danger');
                $(this).removeClass('btn-info');
                $(this).text('禁用');
                // $(this).parent().parent().find('input').attr('disabled', 'disabled');
            }
        })
    })

    /**
     *  生成规格属性
     */
    function ajaxGetSpecGroup(cate_id, goods_id) {
        $.ajax({
            type: 'POST',
            data: {
                cate_id: cate_id
            },
            url: "goods/goods_spec_group/getSpecGroup",
            success: function (res) {
                if(res.code === 1){
                    specGroup = res.data;
                    var $str = '';
                    $str += "<button type='button' class='spec btn btn-success' id='addSpecInput'>增加属性</button>";
                    $str += "<table class='table table-striped table-bordered table-hover table-nowrap'>";
                    $str += "<thead>";
                    $str += "<tr>";
                    $str += "<td><b>序号</b></td>";
                    // $str += "<td><b>订单下推</b></td>";
                    for (let i = 0; i < specGroup.length; i++){
                        $str += "<td><b>"+specGroup[i].spec_name+"</b></td>";
                    }
                    $str += "<td><b>价格</b></td>";
                    $str += "<td><b>库存</b></td>";
                    $str += "<td><b>单位</b></td>";
                    $str += "<td><b>重量(kg)</b></td>";
                    $str += "<td><b>编码</b></td>";
                    $str += "<td><b>图片</b></td>";
                    $str += "<td><b>操作</b></td>";
                    $str += "</tr>";
                    $str += "</thead>";
                    $str += "<tbody id='spec_input_tab'>";
                    $str += "</tbody>";
                    $str += "</table>";
                    $("#goods_spec_table2").html('').append($str);
                    if(!goods_id){
                        ajaxGetSpecInput()
                    }else{
                        ajaxGetSpecInputOld(goods_id)
                    }
                }
            }
        });
    }

    /**
     *  生成已有规格输入框
     */
    function ajaxGetSpecInputOld(goods_id) {
        $.ajax({
            type: 'POST',
            data: {
                ids: goods_id
            },
            url: "goods/goods/spec",
            success: function (res) {
                if(res.code === 1){
                    var data = res.data;
                    var $str = '';
                    for (let spec = 0; spec < data.length; spec++){
                        $str +="<tr class='item_input'>";
                        $str +="<th scope='row' style='width: 30px'>#"+ (spec+1) +"</th>";
                        $str +="<input type='hidden' name='row[item]["+spec+"][goods_spec_id]' value='"+ data[spec].goods_spec_id +"' />";

                        // $str +="<td><input id='c-push-"+spec+"' name='row[item]["+spec+"][push]' type='hidden' value='"+data[spec].push+"'><a href='javascript:;' data-toggle='switcher' class='btn-switcher' data-input-id='c-push-"+spec+"' data-yes='1' data-no='0' >";
                        // if(data[spec].push == 0){
                        //     $str += "<i class='fa fa-toggle-on text-success fa-flip-horizontal text-gray fa-2x'></i></a></td>";
                        // }else{
                        //     $str += "<i class='fa fa-toggle-on text-success fa-2x'></i></a></td>";
                        // }

                        let goods_spec_item = data[spec].goods_spec_item;
                        for (let i = 0; i < specGroup.length; i++){
                            var spec_group_ = '';
                            for (let gsi = 0; gsi < goods_spec_item.length; gsi++){
                                if(goods_spec_item[gsi].spec_group_id == specGroup[i].spec_group_id){
                                    spec_group_ = "<td><input style='width: 80px' type='text' name='row[item]["+spec+"][spec_group_"+ specGroup[i].spec_group_id +"]' value='"+goods_spec_item[gsi].item_name+"' /></td>";
                                }
                            }
                            if(!spec_group_){
                                spec_group_ = "<td><input style='width: 80px' type='text' name='row[item]["+spec+"][spec_group_"+ specGroup[i].spec_group_id +"]' value='' /></td>";
                            }
                            $str += spec_group_;
                        }
                        $str += "<td><input style='width: 80px' type='number' name='row[item]["+spec+"][spec_price]' value='"+ data[spec].spec_price +"'/></td>";
                        $str +="<td><input style='width: 80px' type='number' name='row[item]["+spec+"][spec_stock]' value='"+ data[spec].spec_stock +"'/></td>";
                        $str +="<td><input style='width: 50px' type='text' name='row[item]["+spec+"][unit]' value='"+ data[spec].unit +"'/></td>";
                        $str +="<td><input style='width: 50px' type='text' name='row[item]["+spec+"][weight]' value='"+ data[spec].weight +"'/></td>";
                        $str +="<td><input style='width: 120px' type='text' name='row[item]["+spec+"][goods_spec_sn]' value='"+ data[spec].goods_spec_sn +"'/></td>";

                        $str +="<td><input id='c-spec_image-"+spec+"' type='hidden' name='row[item]["+spec+"][spec_image]' value='"+ data[spec].spec_image +"' />";
                        $str +=     "<span>";
                        $str +=         "<button type='button' id='plupload-spec_image-"+spec+"' class='btn btn-danger plupload list-block' data-input-id='c-spec_image-"+spec+"' data-mimetype='image/gif,image/jpeg,image/png,image/jpg,image/bmp' data-multiple='false' data-preview-id='p-spec_image-"+spec+"'><i class='fa fa-upload'></i> 上传</button>";
                        $str +=         "<button type='button' id='fachoose-spec_image-"+spec+"' class='btn btn-primary fachoose' data-input-id='c-spec_image-"+spec+"' data-preview-id='p-spec_image-"+spec+"' data-mimetype='image/*' data-multiple='false'><i class='fa fa-list'></i> 选择</button>";
                        $str +=     "</span>";
                        $str +="    <ul class='row list-inline plupload-preview p-spec_image' style='' id='p-spec_image-"+spec+"' ></ul>"
                        $str +="</td>";
                        if(data[spec].status === 1){
                            $str +="<td><button type='button' class='btn btn-primary btn-danger delete_item'>禁用</button><input type='hidden' name='row[item]["+spec+"][status]' value='1'></td>";
                        }else{
                            $str +="<td><button type='button' class='btn btn-primary btn-info delete_item'>启用</button><input type='hidden' name='row[item]["+spec+"][status]' value='0'></td>";
                        }

                        $str +="</tr>";
                    }

                    $("#spec_input_tab").append($str);
                    Form.events.plupload($("form[role=form]"));//动态绑定上传按钮
                    Form.events.faselect($("form[role=form]"));//动态绑定选择附件按钮
                }
            }
        });
    }

    /**
     *  生成规格输入框
     */
    function ajaxGetSpecInput() {

        var price = $("#c-price").val();

        var item_key = $(".item_input").length;

        $str ="<tr class='item_input'>";
        $str +="<th scope='row' style='width: 30px'>#"+ (item_key+1) +"</th>";
        $str +="<input type='hidden' name='row[item]["+item_key+"][goods_spec_id]' value='' />";

        // $str +="<td><input id='c-push-"+item_key+"' name='row[item]["+item_key+"][push]' type='hidden' value='0'><a href='javascript:;' data-toggle='switcher' class='btn-switcher' data-input-id='c-push-"+item_key+"' data-yes='1' data-no='0' ><i class='fa fa-toggle-on text-success fa-flip-horizontal text-gray fa-2x'></i></a></td>";

        for (let i = 0; i < specGroup.length; i++){
            $str += "<td><input style='width: 80px' type='text' name='row[item]["+item_key+"][spec_group_"+ specGroup[i].spec_group_id +"]' value='' /></td>";
        }
        $str += "<td><input style='width: 80px' type='number' name='row[item]["+item_key+"][spec_price]' value='"+price+"'/></td>";
        $str +="<td><input style='width: 80px' type='number' name='row[item]["+item_key+"][spec_stock]' value=''/></td>";
        $str +="<td><input style='width: 50px' type='text' name='row[item]["+item_key+"][unit]' value=''/></td>";
        $str +="<td><input style='width: 50px' type='text' name='row[item]["+item_key+"][weight]' value=''/></td>";
        $str +="<td><input style='width: 120px' type='text' name='row[item]["+item_key+"][goods_spec_sn]' value=''/></td>";
        $str +="<td><input id='c-spec_image-"+item_key+"' type='hidden' name='row[item]["+item_key+"][spec_image]' value='' />";
        $str +="<span>";
        $str +="<button type='button' id='plupload-spec_image-"+item_key+"' class='btn btn-danger plupload list-block' data-input-id='c-spec_image-"+item_key+"' data-mimetype='image/gif,image/jpeg,image/png,image/jpg,image/bmp' data-multiple='false' data-preview-id='p-spec_image-"+item_key+"'><i class='fa fa-upload'></i> 上传</button>";
        $str +="<button type='button' id='fachoose-spec_image-"+item_key+"' class='btn btn-primary fachoose' data-input-id='c-spec_image-"+item_key+"' data-preview-id='p-spec_image-"+item_key+"' data-mimetype='image/*' data-multiple='false'><i class='fa fa-list'></i> 选择</button>";
        $str +="</span>";
        $str +="<ul class='row list-inline plupload-preview p-spec_image' style='' id='p-spec_image-"+item_key+"' ></ul></td>";
        $str +="<td><button type='button' class='btn btn-primary btn-danger delete_item'>禁用</button><input type='hidden' name='row[item]["+item_key+"][status]' value='1'></td>";
        $str +="</tr>";
        $("#spec_input_tab").append($str);
        Form.events.plupload($("form[role=form]"));//动态绑定上传按钮
        Form.events.faselect($("form[role=form]"));//动态绑定选择附件按钮
    }

    return Controller;
});
